<?php
//рус
include_once(_APP_PATH. "business/image/image_mapper.php");
class image_media_http_web extends controller_prototype_class
{
    private $_imageInfo = array(); 
    
    protected function ControllerInit ()
    {

    }    
    
    protected function PrimaryActionInit ($basicActionName)
    {
     
    }    

    public function PrAction()
    {
        $this->analysePr();        
    }

    public function analysePrAction()
    {
        list($requestUri) = explode('?', $this->Request()->getRequestUri());
        $filePath = ltrim($requestUri, '/');
        $pathParts = pathinfo($filePath);
        
        if (0 !== strpos($filePath, MozfgCfg::GetProp('global/image//imageThumbsFolder')) ||
            !in_array($pathParts['extension'], MozgCfg::GetProp('global//mediaFilesExtensions')))
        {
            $this->_ctrls->errors->NotFoundPr();
            return;                      
        } 

        $imageFolder = substr($pathParts['dirname'], strlen(MozgCfg::GetProp('global/image//imageThumbsFolder')));
        list($thumbFolder, $imageFolder) = explode('/', $imageFolder, 2);
        $originalFilePath = _ROOT_PATH.$imageFolder. '/' .$pathParts['basename'];
        
        $imageFileObj = $this->Libs()->image->GetImage($originalFilePath);
        
        $mapper = ImageMapper::GetInstance();
        
        if (!$mapper->IsThumbFolder($thumbFolder) || !$imageFileObj->IsImage())
        {
            $this->_ctrls->errors->NotFoundPr();
            return;             
        }

        $thumbPath = _ROOT_PATH.$mapper->GetImageThumbFolder($thumbFolder, $imageFolder);

        if (!$this->Libs()->dir->Create($thumbPath))
        {
            $this->_ctrls->errors->NotFoundPr();
            return;               
        }
        
        $folderSize = $mapper->GetThumbFolderSizes($thumbFolder);
		$imageFileObj->Resize($thumbPath, $pathParts['basename'], $folderSize['size'], false, false, $folderSize['saveProportions']); 
		
		if ($imageFileObj->IsError()) 
		{    
            $this->_ctrls->errors->NotFoundPr();
            return; 
		} 
/*
        $f = fopen('testimage.log', 'a+t');
        fwrite($f, $originalFilePath. "\n");
        fclose($f);		
*/		
		$info = getimagesize($thumbPath.$pathParts['basename']);
		$info['filesize'] = filesize($thumbPath.$pathParts['basename']);
		$this->SetImageInfo($info);
		
		$this->GetModule()->GetDecorator()->SetTemplate('Image')
		                             	  ->SetSecondAction('imageInfo', 'GetImageInfo', 'image');
		
		$this->Response()->TurnCompression(false);
        $this->Response()->SetBody(file_get_contents($thumbPath.$pathParts['basename']));		
    }
    
    private function SetImageInfo($info)
    {
        $this->_imageInfo = $info;        
    }

    public function GetImageInfo()
    {
        return $this->_imageInfo;        
    }       
}    